import axios from 'axios'
import fs from 'fs'
import path from 'path'
import { chromium } from 'playwright'
import { dataDir } from '../config.js'

/**
 * 将网页或PDF转换为PDF文件
 * @param {string} url - 网页URL或PDF链接
 * @param {string} outputPath - 输出PDF文件的路径（可选）
 * @returns {Promise<string>} - 返回生成的PDF文件路径
 */
export async function convertWebpageOrPdfToPdf(url, outputPath = null) {
  try {
    console.log(`🔗 处理URL: ${url}`)

    // 检查URL是否以.pdf结尾
    if (url.toLowerCase().endsWith('.pdf')) {
      console.log('检测到PDF链接，直接下载...')
      // return await downloadPdf(url, outputPath)
      await downloadFile(url, outputPath)
    } else {
      console.log('检测到网页链接，使用Playwright转换为PDF...')
      await convertWebpageToPdf(url, outputPath)
    }

    console.log(`✅ 下载完成: ${outputFile}`)
  } catch (err) {
    // console.error('处理URL时出错:', error.message)
    console.error(`❌ 下载出错: ${err.message}`, outputPath)
    throw err
  }
}

/**
 * 直接下载PDF文件
 * @param {string} pdfUrl - PDF文件的URL
 * @param {string} outputPath - 输出路径
 * @returns {Promise<string>} - 返回下载的PDF文件路径
 */
async function downloadPdf(pdfUrl, outputPath = null) {
  const outputFile = outputPath || generateOutputPath(pdfUrl, 'pdf')

  const response = await axios({
    method: 'GET',
    url: pdfUrl,
    responseType: 'stream',
  })

  const writer = fs.createWriteStream(outputFile)

  response.data.pipe(writer)

  return new Promise((resolve, reject) => {
    writer.on('finish', () => {
      console.log(`PDF下载完成: ${outputFile}`)
      resolve(outputFile)
    })
    writer.on('error', reject)
  })
}

/**
 * 使用Playwright将网页转换为PDF
 * @param {string} url - 网页URL
 * @param {string} outputPath - 输出路径
 * @returns {Promise<string>} - 返回生成的PDF文件路径
 */
async function convertWebpageToPdf(url, outputPath = null) {
  const outputFile = outputPath || generateOutputPath(url, 'pdf')
  const browser = await chromium.launch({
    headless: false,
  })
  const context = await browser.newContext()
  const page = await context.newPage()

  try {
    // 导航到页面
    await page.goto(url, { waitUntil: 'networkidle', timeout: 180 * 1000 })

    // 生成PDF
    await page.pdf({
      path: outputFile,
      format: 'A4',
      printBackground: true,
      margin: {
        top: '1cm',
        right: '1cm',
        bottom: '1cm',
        left: '1cm',
      },
    })

    console.log(`网页已成功转换为PDF: ${outputFile}`)
    return outputFile
  } finally {
    // 确保浏览器被关闭
    await browser.close()
  }
}

/**
 * 生成输出文件路径
 * @param {string} url - URL
 * @param {string} extension - 文件扩展名
 * @returns {string} - 输出文件路径
 */
function generateOutputPath(url, extension) {
  // const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  // const domain = new URL(url).hostname
  // const filename = `${domain}_${timestamp}.${extension}`
  const filename = md5(url) + '.' + extension
  return path.join(dataDir, filename)
}

/**
 * 检查URL是否为PDF
 * @param {string} url - URL
 * @returns {boolean} - 是否为PDF
 */
function isPdfUrl(url) {
  return url.toLowerCase().endsWith('.pdf')
}

// 使用示例
async function main() {
  try {
    // 示例1: 转换网页为PDF
    const webpageUrl = 'https://example.com'
    const pdfPath1 = await convertWebpageOrPdfToPdf(webpageUrl)
    console.log('生成的PDF:', pdfPath1)

    // 示例2: 直接下载PDF
    const pdfUrl = 'https://example.com/document.pdf'
    const pdfPath2 = await convertWebpageOrPdfToPdf(pdfUrl)
    console.log('下载的PDF:', pdfPath2)
  } catch (error) {
    console.error('错误:', error.message)
  }
}

// 如果需要直接运行测试，取消下面的注释
// main();

export async function downloadFile(url, outputPath) {
  const browser = await chromium.launch()
  const context = await browser.newContext()
  const request = context.request
  const outputFile = outputPath || generateOutputPath(url, 'pdf')

  try {
    const response = await request.get(url)

    if (!response.ok()) {
      throw new Error(`下载失败: ${response.status()} - ${response.statusText()}`)
    }

    const buffer = await response.body()
    fs.writeFileSync(outputFile, buffer)
  } catch (err) {
    throw err
  } finally {
    await browser.close()
  }
}

// downloadFile(
//   'https://www.bitdefender.com/files/News/CaseStudies/study/379/Bitdefender-Whitepaper-Chinese-APT.pdf',
//   '1.pdf'
// )
